﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>职称设置</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@3.3.4/dist/vue.global.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/element-plus/dist/index.full.min.js"></script>
    <style>
        .page-container {
            margin-top: 20px;
            display: flex;
            justify-content: center;
        }

        body {
            background-color: #FFFFCC;
        }

        .caozuo {
            margin: 5px;
        }
    </style>
</head>
<body>
    <div id="app">
        <div>您正在做的业务是：人力资源--权限管理--添加角色</div>
        <div class="caozuo">
            <button v-on:click="Upd">保存</button> &nbsp;&nbsp;
            <button v-on:click="Fan">返回</button>
        </div>
        <table>
            <tr>
                <td>角色编号：</td>
                <td width="400px">{{id}}</td>
                <td>角色名称：</td>
                <td width="400px"><el-input v-model="name"></el-input></td>
            </tr>
            <tr>
                <td>角色说明：</td>
                <td><el-input v-model="sm"></el-input></td>
                <td>角色是否可用：</td>
                <td>
                    <el-select v-model="value"
                               placeholder="请选择"
                               size="large"
                               style="width: 150px;">
                        <el-option v-for="item in options"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="item.value" />
                    </el-select>
                </td>
            </tr>
        </table>
        <div>
            <el-tree ref="permissionTree"
                     style="width: 100%;background-color: #FFFFCC;"
                     :props="props"
                     :load="loadNode"
                     lazy
                     show-checkbox
                     v-on:check-change="handleCheckChange"
                     v-on:node-load="handleNodeLoad" />  <!-- 新增节点加载完成事件 -->
        </div>
    </div>
    <script>
        const { createApp, ref, onMounted, nextTick } = Vue;

        const app = createApp({
            setup() {
                const id = ref('')
                const name = ref('')
                const sm = ref('')
                const value = ref('True');
                const options = [
                    { value: "True", label: "是" },
                    { value: "False", label: "否" }
                ];

                const props = ref({
                    label: 'JurName',
                    children: 'children',
                    isLeaf: 'leaf'
                });

                const checkedKeys = ref([]);
                const permissionTree = ref(null);
                // 新增：标记是否需要设置选中状态（解决异步时序问题）
                const needSetChecked = ref(false);

                const jurisdictionData = [
                    // 权限数据保持不变...
                    { JuriID: 1, JurName: '招聘管理', GroupID: 0, JurAddress: '0' },
                    { JuriID: 2, JurName: '人力资源档案管理', GroupID: 0, JurAddress: '0' },
                    { JuriID: 3, JurName: '薪酬标准管理', GroupID: 0, JurAddress: '0' },
                    { JuriID: 4, JurName: '薪酬发放管理', GroupID: 0, JurAddress: '0' },
                    { JuriID: 5, JurName: '调动管理', GroupID: 0, JurAddress: '0' },
                    { JuriID: 6, JurName: '客户化设置', GroupID: 0, JurAddress: '0' },
                    { JuriID: 7, JurName: '权限管理', GroupID: 0, JurAddress: '0' },
                    { JuriID: 8, JurName: '职位发布管理', GroupID: 1, JurAddress: '0' },
                    { JuriID: 9, JurName: '简历管理', GroupID: 1, JurAddress: '0' },
                    { JuriID: 10, JurName: '面试管理', GroupID: 1, JurAddress: '0' },
                    { JuriID: 11, JurName: '录用管理', GroupID: 1, JurAddress: '0' },
                    { JuriID: 12, JurName: '人力资源档案登记', GroupID: 2, JurAddress: 'HRFR/Index' },
                    { JuriID: 13, JurName: '人力资源档案登记复核', GroupID: 2, JurAddress: 'HRFR/RLFH' },
                    { JuriID: 14, JurName: '人力资源档案查询', GroupID: 2, JurAddress: 'RLCX/Index2' },
                    { JuriID: 15, JurName: '人力资源档案变更', GroupID: 2, JurAddress: 'RLBG/Index1' },
                    { JuriID: 16, JurName: '人力资源档案删除管理', GroupID: 2, JurAddress: '0' },
                    { JuriID: 17, JurName: '薪酬标准登记', GroupID: 3, JurAddress: 'SS_Insert/Index' },
                    { JuriID: 18, JurName: '薪酬标准登记复核', GroupID: 3, JurAddress: 'SS_Server/Index' },
                    { JuriID: 19, JurName: '薪酬标准查询', GroupID: 3, JurAddress: 'SS_Search/Index' },
                    { JuriID: 20, JurName: '薪酬标准变更', GroupID: 3, JurAddress: 'SS_Alteration/Index' },
                    { JuriID: 21, JurName: '薪酬发放登记', GroupID: 4, JurAddress: 'SDM_insert/Index' },
                    { JuriID: 22, JurName: '薪酬发放登记复核', GroupID: 4, JurAddress: 'SDM_select/Index' },
                    { JuriID: 23, JurName: '薪酬发放查询', GroupID: 4, JurAddress: 'SDM_sct/Index' },
                    { JuriID: 24, JurName: '调动登记', GroupID: 5, JurAddress: 'DDDJ/CX' },
                    { JuriID: 25, JurName: '调动审核', GroupID: 5, JurAddress: 'DDSH/SHYM' },
                    { JuriID: 26, JurName: '调动查询', GroupID: 5, JurAddress: 'DDSelect/CXYM' },
                    { JuriID: 27, JurName: '人力资源档案管理设置', GroupID: 6, JurAddress: '0' },
                    { JuriID: 28, JurName: '薪酬管理设置', GroupID: 6, JurAddress: '0' },
                    { JuriID: 29, JurName: '用户管理', GroupID: 7, JurAddress: 'User_Manage/Index' },
                    { JuriID: 30, JurName: '角色管理', GroupID: 7, JurAddress: 'Role_Permissions/Index' },
                    { JuriID: 31, JurName: '职位发布登记', GroupID: 8, JurAddress: 'EMR_Add/Index' },
                    { JuriID: 32, JurName: '职位发布变更', GroupID: 8, JurAddress: 'EMR_SUD/Index' },
                    { JuriID: 33, JurName: '职位发布查询', GroupID: 8, JurAddress: 'EMR_Select/Index' },
                    { JuriID: 34, JurName: '简历登记', GroupID: 9, JurAddress: 'ER_Add/Index' },
                    { JuriID: 35, JurName: '简历筛选', GroupID: 9, JurAddress: 'ER_Select/Index' },
                    { JuriID: 36, JurName: '有效简历查询', GroupID: 9, JurAddress: 'ER_YxSelect/Index' },
                    { JuriID: 37, JurName: '面试结果登记', GroupID: 10, JurAddress: 'ERAndEI_AUS/Index' },
                    { JuriID: 38, JurName: '面试筛选', GroupID: 10, JurAddress: 'EI_SX/Index' },
                    { JuriID: 39, JurName: '录用申请', GroupID: 11, JurAddress: 'ER_LYSQ/Index' },
                    { JuriID: 40, JurName: '录用审批', GroupID: 11, JurAddress: 'ER_LYSP/Index' },
                    { JuriID: 41, JurName: '录用查询', GroupID: 11, JurAddress: 'ER_LYCX/Index' },
                    { JuriID: 42, JurName: '人力资源档案删除', GroupID: 16, JurAddress: 'DASC/SCCK' },
                    { JuriID: 43, JurName: '档案删除恢复', GroupID: 16, JurAddress: 'DASC/DAHF' },
                    { JuriID: 44, JurName: '人力资源档案永久删除', GroupID: 16, JurAddress: 'DASC/DSSC' },
                    { JuriID: 45, JurName: 'Ⅰ级机构设置', GroupID: 27, JurAddress: 'JGSZI/Index' },
                    { JuriID: 46, JurName: 'Ⅱ级机构设置', GroupID: 27, JurAddress: 'EJJGSZ/Index' },
                    { JuriID: 47, JurName: 'Ⅲ级机构设置', GroupID: 27, JurAddress: 'SJJGSZ/Index' },
                    { JuriID: 48, JurName: '职称设置', GroupID: 27, JurAddress: 'ZCSZ/Index' },
                    { JuriID: 49, JurName: '职位分类设置', GroupID: 27, JurAddress: 'ZWFLSZ/Index' },
                    { JuriID: 50, JurName: '职位设置', GroupID: 27, JurAddress: 'ZWSZ/Index' },
                    { JuriID: 51, JurName: '公共属性设置', GroupID: 27, JurAddress: 'CPC/Index' },
                    { JuriID: 52, JurName: '薪酬项目设置', GroupID: 28, JurAddress: 'SSD/Index' }
                ];

                function loadNode(node, resolve) {
                    const parentId = node.level === 0 ? 0 : node.data.JuriID;
                    const children = jurisdictionData
                        .filter(item => item.GroupID === parentId)
                        .map(item => ({
                            JuriID: item.JuriID,
                            JurName: item.JurName,
                            JurAddress: item.JurAddress,
                            leaf: item.JurAddress !== '0',
                            children: item.JurAddress === '0' ? [] : null,
                            // 关键：加载节点时直接判断是否需要选中
                            checked: checkedKeys.value.includes(item.JuriID)
                        }));

                    setTimeout(() => {
                        resolve(children);
                    }, 300);
                }

                // 新增：节点加载完成后触发
                function handleNodeLoad(node, data) {
                    // 如果已经获取到权限列表，就设置选中状态
                    if (checkedKeys.value.length > 0) {
                        nextTick(() => {
                            setTreeChecked(checkedKeys.value);
                        });
                    }
                }

                // 新增：递归获取所有子节点ID
                function getChildIds(parentId) {
                    const children = jurisdictionData.filter(item => item.GroupID === parentId);
                    let childIds = [];
                    children.forEach(child => {
                        childIds.push(child.JuriID);
                        // 递归查询子节点的子节点
                        childIds = [...childIds, ...getChildIds(child.JuriID)];
                    });
                    return childIds;
                }

                // 修改：处理勾选变更，包含子节点和父节点逻辑
                function handleCheckChange(data, checked, indeterminate) {
                    if (checked) {
                        // 勾选时，添加当前节点及其所有子节点（无论是否展开）
                        const allChildIds = getChildIds(data.JuriID);
                        [data.JuriID, ...allChildIds].forEach(id => {
                            if (!checkedKeys.value.includes(id)) {
                                checkedKeys.value.push(id);
                            }
                        });

                        // 新增：勾选所有父节点
                        addParentNodes(data.JuriID);
                    } else {
                        // 取消勾选时，移除当前节点及其所有子节点
                        const allChildIds = getChildIds(data.JuriID);
                        [data.JuriID, ...allChildIds].forEach(id => {
                            const index = checkedKeys.value.indexOf(id);
                            if (index !== -1) {
                                checkedKeys.value.splice(index, 1);
                            }
                        });
                    }
                    console.log('当前选中的节点ID:', checkedKeys.value);
                }

                // 新增：递归添加所有父节点
                function addParentNodes(juriId) {
                    // 查找当前节点的父节点
                    const parentItem = jurisdictionData.find(item => {
                        // 查找GroupID等于当前节点JuriID的项
                        const children = jurisdictionData.filter(child => child.GroupID === item.JuriID);
                        return children.some(child => child.JuriID === juriId);
                    });

                    // 如果找到父节点且未被选中，则添加并继续处理其父节点
                    if (parentItem && !checkedKeys.value.includes(parentItem.JuriID)) {
                        checkedKeys.value.push(parentItem.JuriID);
                        addParentNodes(parentItem.JuriID);
                    }
                }

                onMounted(() => {
                    const urlParams = new URLSearchParams(window.location.search);
                    id.value = urlParams.get('id') || '1';
                    sel();

                    // 先获取权限ID列表，标记需要设置选中状态
                    getCheckedJuris(id.value).then(res => {
                        if (res.data && res.data.zhi && res.data.zhi.length > 0) {
                            checkedKeys.value = res.data.zhi;
                            needSetChecked.value = true; // 标记需要设置选中

                            // 强制展开所有父节点（关键：确保子节点被加载）
                            expandAllParentNodes();
                        }
                    });
                });

                // 新增：强制展开所有父节点（确保子节点加载）
                function expandAllParentNodes() {
                    nextTick(() => {
                        const tree = permissionTree.value;
                        if (!tree) return;

                        // 先展开根节点的所有一级子节点
                        tree.root.childNodes.forEach(node => {
                            tree.expandNode(node.data);
                        });

                        // 延迟足够时间确保所有节点加载完成
                        setTimeout(() => {
                            if (needSetChecked.value) {
                                setTreeChecked(checkedKeys.value);
                            }
                        }, 1000); // 1秒延迟确保节点加载完成
                    });
                }

                function getCheckedJuris(roleId) {
                    return axios.get("/Role_Permissions/getCheckedJuris", {
                        params: { id: roleId }
                    });
                }

                // 修改：更可靠的设置选中状态方法
                function setTreeChecked(checkedIds) {
                    const tree = permissionTree.value;
                    if (!tree) return;

                    // 直接使用tree的内部方法设置选中
                    checkedIds.forEach(juriId => {
                        // 查找节点数据
                        const findNode = (nodes) => {
                            for (const node of nodes) {
                                if (node.JuriID === juriId) return node;
                                if (node.children && node.children.length) {
                                    const found = findNode(node.children);
                                    if (found) return found;
                                }
                            }
                            return null;
                        };

                        // 从根节点开始查找
                        const nodeData = findNode(tree.root.childNodes.map(n => n.data));
                        if (nodeData) {
                            tree.setChecked(nodeData, true, true);
                        }
                    });
                }

                function sel() {
                    axios.get("/Role_Permissions/selectById", {
                        params: { id: id.value }
                    })
                    .then(res => {
                        name.value = res.data.zhi.rolesName;
                        sm.value = res.data.zhi.rolesInstruction;
                        value.value = res.data.zhi.rolesIf;
                    });
                }

                function Upd() {
                    axios.post("/Role_Permissions/Add_RJ", {
                        id: id.value,
                        list: checkedKeys.value
                    })
                    .then(res => {
                        if (res.data.zhi == "ok") {
                            ElementPlus.ElMessage.success('保存成功');
                            setTimeout(() => Fan(), 500);
                        }
                    })
                    .catch(error => {
                        console.error('保存失败:', error);
                        ElementPlus.ElMessage.error('保存失败，请重试');
                    });
                }

                function Fan() {
                    window.location.href = `/Role_Permissions/Index`;
                }

                return {
                    Fan, Upd, value, options, name, sm, id,
                    props, loadNode, handleCheckChange,
                    permissionTree, handleNodeLoad  // 新增返回事件处理
                };
            }
        });

        app.use(ElementPlus);
        app.mount('#app');
    </script>
</body>
</html>    